<?
/**
 * DataRow models a database table row. It is an implementation of the Row Data Gateway pattern.
 *
 * The idea behind is to have an object that maps one and only one row from a table.
 * The class generates all the object properties dynamically, usings the field names from the table.
 *
 * Example of usage:
 *
 * Suppose we have table Person with the fields PersonID, Name, LastName, Telephone and Age.
 * The table key is PersonID.
 *
 * The code to load a record where PersonID is 4 would be:
 *  <code>
 *		// The constructor takes as arguments the table name and the table key.
 *      $p = new DataRow("Person", "PersonID");
 *      $p->load(4); // load() uses the key PersonID to load the record...
 *  </code>
 *
 * With that we have the $p object with all the fields loaded, so now we can do things like this:
 *
 *  <code>
 *      echo $p->Name:
 *      echo $p->LastName;
 *  </code>
 * If we want to modify a property and save it:
 * <code>
 *      $p->Age = 45;
 *      $p->save();
 * </code>
 * The save() method is used when the key property has a value defined. If the key is autoincremental, then you must
 * create the new record using insert(), not save(). Now, if the key is not autoincremental, you can create the
 * new record just using save() directly, but you must have the key field defined.
 * So, if PersonID is not autoincremental, creating a new record is very easy:
 * (Note we are not using load()!)
 *  <code>
 *      $p = new DataRow("Persona", "PersonaID");
 *      $p->PersonID = 45;
 *      $p->Name = "Winston";
 *      $p->LastName = "Churchill";
 *      $p->save();
 *  </code>
 *
 * The class also supports multiple keys. You must specify the key with an array. When using the load() method,
 * you must pass the key values into an array.
 * Example:
 *
 *  <code>
 *      $p = new DataRow("Persona", array("Name", "LastName"));
 *      $p->load(array("Name"=>"Winston", "LastName"=>"Churchill"));
 *  </code>
 * @author Juan Vassallo <jvassallo@adverit.com>
 * @version 1.0
 * @package database
 * 
 */
class DataRow
{

    public $_dbTable = "";
    public $_dbIndex = array();
    public $_autoField = "";

    public function __construct($tableName, $index="")
    {
        global $dbLink;
        $this->_dbLink = $dbLink;
        $this->_dbTable = $tableName;
        if(is_array($index)) $this->_dbIndex = $index;
        else $this->_dbIndex[] = $index;
    }

    private function getSqlCondition($param)
    {
        $condition = "";
        if(is_array($param))
        {
            $condition =  " WHERE 1";
            foreach($this->_dbIndex as $key) 
            {
                $condition .= " AND `".$key."`='" . $param[$key] . "'";
            }
        }
        else 
        { // si no es un array, el index tiene un solo campo
            $condition =  " WHERE `".$this->_dbIndex[0] ."` = '".$param."'";
        }
        return $condition;
    }
/**
* Loads the data corresponding to param from table and generates dynamic properties.
* 
* @param string|integer|array
* @return bool
*/

    public function load($param) 
    {
        if(count($this->_dbIndex)==0) return;
        $condition = $this->getSqlCondition($param);
        if(is_array($param)) 
        {
            foreach($param as $k=>$v) $this->$k = $v;
        }
        else 
        {
            $key = $this->_dbIndex[0];
            $this->$key = $param;
        }

        $result = mysql_query("SELECT * FROM " . $this->_dbTable . $condition, $this->_dbLink);
        if(!$result) return false;
        $row = mysql_fetch_assoc($result);
        
        if(mysql_num_rows($result)==0) return false;
        
        foreach($row as $k=>$v) $this->$k = $v;
        
        return true;
    }

    public function save()
    {
        if(count($this->_dbIndex)==0) return;
        
        $condition = $this->getSqlCondition((array)$this);
        $sql = "UPDATE ".$this->_dbTable." SET ";
        
        foreach((array)$this as $k=>$v) if($k{0}!="_")  $sql .= "`". $k ."`='". txt2sql($v) ."', ";
        
        $sql{strlen($sql) - 2} = " ";
       
        mysql_query( $sql . $condition, $this->_dbLink);
        
        if(mysql_affected_rows() <= 0) return $this->insert();
		return true;
    }

    public function delete()
    {
        if(count($this->_dbIndex)==0) return;
        
        $condition = $this->getSqlCondition((array)$this);
        $sql = "DELETE FROM " . $this->_dbTable . $condition;
        mysql_query($sql, $this->_dbLink);
    }

    public function insert()
    {
        $o = array();
        foreach((array) $this as $k=>$v) if($k{0}!="_") $o[$k] = $v;

		$values = '';
		foreach((array) $this as $k => $v) 
		{
			if($k{0} != "_")	$values .= "'". txt2sql($v) ."', ";
		}
        $values{strlen($values) - 2} = " ";

        $sql = "INSERT INTO " . $this->_dbTable . " (" . implode(", " ,array_keys($o)) . ") values (" . $values . ")";
        $retval = mysql_query($sql, $this->_dbLink);
        if($this->_autoField!="") {
            $auto = $this->_autoField;
            $this->$auto = mysql_insert_id();
        }
        return $retval;
    }

}
?>
